import HandleBtn from '@/components/HandleBar/btn';
import {
  ActionType,
  ModalForm,
  ProColumns,
  ProFormDatePicker,
  ProFormDigit,
  ProFormSelect,
  ProFormTimePicker,
  ProTable,
} from '@/components/Pro/';
import { TIME_TYPE } from '@/dictionary';
import {
  stationFeeControllerAddFee as add,
  stationFeeControllerBatch as batchHandle,
  stationFeeControllerDownloadExcel as downloadFile,
  stationFeeControllerEditFee as edit,
  stationFeeControllerList as getList,
  stationFeeControllerUploadExcel as uploadFile,
} from '@/services/ess/stationFee';
import { downloadFetch } from '@/utils/downloadFile';
import type { UploadProps } from 'antd';
import { message, Modal, Space, Upload } from 'antd';
import React, { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { getIntl, useIntl } from 'umi';
import './ElectricityPrice.less';

const { confirm } = Modal;

/**
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.StationFeeReq) => {
  try {
    const res = await add({
      ...fields,
    });
    if (res.success) {
      message.success(getIntl().formatMessage({ id: 'global.addSuccessfully' }));
      return true;
    }
    return false;
  } catch (error) {
    message.error(getIntl().formatMessage({ id: 'global.addFailedTips' }));
    return false;
  }
};

/**
 * @zh-CN 编辑节点
 * @param fields
 */
const handleEdit = async (fields: API.StationFeeReq) => {
  try {
    const res = await edit({
      ...fields,
    });
    if (res.success) {
      message.success(getIntl().formatMessage({ id: 'global.editedDuccessfully!' }));
      return true;
    }
    return false;
  } catch (error) {
    message.error(getIntl().formatMessage({ id: 'global.editFailedTips' }));
    return false;
  }
};

const CollectingArchives: React.FC<{
  id: number | string;
  disableEdit?: boolean;
}> = ({ id, disableEdit }, ref) => {
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.StationFeeReq>({});
  const [selectedRowsState, setSelectedRows] = useState<API.StationFeeReq[]>([]);
  const [disabled, setDisabled] = useState(false);
  const intl = useIntl();

  /**
   * @zh-CN 批量操作
   * @param type
   * @param selectedRows
   */
  function handleBatch(type: API.BatchOperatorReq.type, record = selectedRowsState) {
    if (record.length < 1) {
      message.warning(intl.formatMessage({ id: 'global.leastOne' }));
      return;
    }
    if (disabled) return;
    setDisabled(true);
    confirm({
      title: intl.formatMessage({ id: 'systemManagement.supplementary.prompt' }),
      content:
        type === 'DELETE'
          ? '数据删除后将不可恢复，是否删除？'
          : intl.formatMessage({
              id: 'systemManagement.supplementary.doYouWantToChangeTheEnabledStatusOfThisData',
            }),
      onOk: async () => {
        const res = await batchHandle({
          ids: record.map((row) => row.id),
          type,
        });
        if (res.success) {
          message.success(
            `${
              (type === 'DELETE' &&
                intl.formatMessage({ id: 'systemManagement.supplementary.delete' })) ||
              (type === 'OPEN' &&
                intl.formatMessage({ id: 'systemManagement.generalProcedure.enable' })) ||
              (type === 'DISABLE' &&
                intl.formatMessage({ id: 'systemManagement.generalProcedure.disable' }))
            }成功！`,
          );
          actionRef.current?.reloadAndRest?.();
        }
      },
      afterClose: () => {
        setDisabled(false);
      },
    });
  }

  useImperativeHandle(ref, () => ({
    handleBatch,
    add: () => {
      setCurrentRow({});
      handleModalOpen(true);
    },
    selectedRowsState,
    customRequest: async (info) => {
      const form = new FormData();
      form.append('file', info.file);
      const res = await uploadFile({ stationId: Number(id) }, form, { ingoreErrorMsg: true });
      if (res?.success) {
        message.success(`${info.file.name} 文件导入成功`);
        actionRef?.current?.reloadAndRest?.();
        return;
      }
      const msg = res?.message;
      message.error(`${info.file.name} 文件导入失败 ${msg ? ',' + msg : ''}`);
    },
    download: () => {
      downloadFetch(downloadFile, { stationId: id });
    },
  }));

  const columns: ProColumns<API.StationFeeReq>[] = [
    {
      title: intl.formatMessage({ id: 'systemManagement.generalProcedure.SN' }),
      hideInSearch: true,
      render: (dom, entity, index) => index + 1,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.siteAdministrationMenu.month' }),
      dataIndex: 'months',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.siteAdministrationMenu.timeperiod' }),
      dataIndex: 'startTime',
      hideInSearch: true,
      render: (_, record) => `${record.startTime} - ${record.endTime}`,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.siteAdministrationMenu.Timeperiodtype' }),
      dataIndex: 'timeType',
      valueEnum: TIME_TYPE,
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.siteAdministrationMenu.Electricityprice' }),
      dataIndex: 'fee',
      hideInSearch: true,
    },
  ];

  if (!disableEdit) {
    columns.push({
      title: intl.formatMessage({ id: 'systemManagement.generalProcedure.operation' }),
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space>
          <a
            key="edit"
            onClick={() => {
              handleModalOpen(true);
              setCurrentRow(record);
            }}
          >
            {intl.formatMessage({ id: 'systemManagement.generalProcedure.edit' })}
          </a>
          <a
            key="delete"
            className="global-del-color"
            onClick={() => handleBatch('DELETE', [record])}
          >
            {intl.formatMessage({ id: 'systemManagement.generalProcedure.delete' })}
          </a>
        </Space>
      ),
    });
  }
  return (
    <div>
      <ProTable<API.StationFeeReq, API.PageParams>
        headerTitle={false}
        actionRef={actionRef}
        rowKey="id"
        params={{
          stationId: id,
        }}
        request={getList}
        columns={columns}
        rowSelection={
          !disableEdit && {
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }
        }
        search={false}
        toolBarRender={false}
        cardProps={false} //去掉Card的padding
      />
      <ModalForm
        modalProps={{
          destroyOnClose: true,
        }}
        initialValues={{
          ...currentRow,
          months: currentRow?.months?.split(','),
          rangeTime: [currentRow.startTime, currentRow.endTime],
          timeType: currentRow?.timeType?.toString(),
        }}
        title={currentRow?.id ? '编辑时间段' : '新增时间段'}
        width="730px"
        colProps={{ md: 12 }}
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          let success;
          value.stationId = id;
          value.months = value.months.join(',');
          value.startTime = value.rangeTime[0];
          value.endTime = value.rangeTime[1];
          delete value.rangeTime;
          // TODO month 格式也许需要处理
          if (currentRow?.id) {
            success = await handleEdit({ ...currentRow, ...value } as API.StationFeeReq);
          } else {
            success = await handleAdd(value as API.StationFeeReq);
          }
          if (success) {
            handleModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormDatePicker.Month
          name="months"
          label={intl.formatMessage({ id: 'systemManagement.siteAdministrationMenu.month' })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'systemManagement.requiredFields.month' }),
            },
          ]}
          fieldProps={{
            format: 'M',
            multiple: true,
            style: {
              width: '100%',
            },
            popupClassName: 'electricity-price-month-picker',
          }}
        />
        <ProFormTimePicker.RangePicker
          name="rangeTime"
          label={intl.formatMessage({ id: 'systemManagement.siteAdministrationMenu.timeperiod' })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'systemManagement.requiredFields.timePeriod' }),
            },
          ]}
        />
        <ProFormSelect
          label={intl.formatMessage({
            id: 'systemManagement.siteAdministrationMenu.Timeperiodtype',
          })}
          name="timeType"
          valueEnum={TIME_TYPE}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'systemManagement.requiredFields.timePeriodType' }),
            },
          ]}
        />
        <ProFormDigit
          label={intl.formatMessage({
            id: 'systemManagement.siteAdministrationMenu.Electricityprice',
          })}
          name="fee"
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'systemManagement.requiredFields.electricityPrice',
              }),
            },
          ]}
          fieldProps={{
            precision: 6,
            min: 0.000001,
            max: 1000000000,
          }}
        />
      </ModalForm>
    </div>
  );
};

export type ToolBarProps = {
  tableRef: React.MutableRefObject<null>;
};
const ToolBarRender: React.FC<ToolBarProps> = ({ tableRef }) => {
  const props: UploadProps = {
    name: 'file',
    multiple: true,
    showUploadList: false,
    customRequest: (info) => tableRef?.current?.customRequest(info),
  };
  const intl = useIntl();

  return (
    <>
      <HandleBtn
        handleType="add"
        key="add"
        onClick={() => {
          tableRef?.current?.add();
        }}
      >
        {intl.formatMessage({ id: 'systemManagement.generalProcedure.new' })}
      </HandleBtn>
      <Upload {...props} key="import">
        <HandleBtn handleType="import">
          {' '}
          {intl.formatMessage({ id: 'systemManagement.generalProcedure.import' })}
        </HandleBtn>
      </Upload>
      <HandleBtn handleType="export" key="export" onClick={() => tableRef?.current?.download()}>
        {intl.formatMessage({ id: 'systemManagement.generalProcedure.export' })}
      </HandleBtn>
      <HandleBtn
        onClick={() => {
          tableRef?.current?.handleBatch('DELETE');
        }}
        handleType="delete"
        key="delete"
      >
        {intl.formatMessage({ id: 'systemManagement.generalProcedure.batchDelete' })}
      </HandleBtn>
    </>
  );
};

export default forwardRef(CollectingArchives);
export { ToolBarRender };
